package fm.dongman.modellib.source;

import android.support.annotation.NonNull;

import java.util.List;

import fm.dongman.animefm.contractlib.BaseDataSource;
import fm.dongman.animefm.contractlib.IModel;
import fm.dongman.animefm.contractlib.contract.ComicContract;
import fm.dongman.animefm.contractlib.model.ComicDataModel;
import fm.dongman.modellib.local.ComicLocalDataSource;
import fm.dongman.modellib.remote.ComicRemoteDataSource;

/**
 * 番剧数据操作
 * Created by KUIGE on 2017/10/17.
 */

public class ComicRepository implements ComicContract.IComicDataSource {
    private static ComicRepository SINGLETON; // 实例
    private ComicRemoteDataSource mRemote;
    private ComicLocalDataSource mLocal;

    private ComicRepository(ComicRemoteDataSource instance, ComicLocalDataSource comicLocalDataSource) {
        mRemote = instance;
        mLocal = comicLocalDataSource;
    }

    public static ComicRepository getInstance(ComicRemoteDataSource instance, ComicLocalDataSource comicLocalDataSource) {
        if (SINGLETON == null) {
            SINGLETON = new ComicRepository(instance, comicLocalDataSource);
        }
        return SINGLETON;
    }

    @Override
    public void getComicGuessLike(@NonNull BaseDataSource.LoadSourceCallback<? super List<? extends IModel.IComicModel>> callback) {
        mRemote.getComicGuessLike(callback);
    }

    @Override
    public void getData(@NonNull final BaseDataSource.LoadSourceCallback<? super ComicDataModel> callback) {
        mRemote.getData(new LoadSourceCallback<ComicDataModel>() {
            @Override
            public void onDataLoaded(ComicDataModel dataModel) {
                callback.onDataLoaded(dataModel);
            }

            @Override
            public void onDataLoadFiled() {
                loadLocalData(callback);
            }
        });
    }

    /**
     * 加载本地
     *
     * @param callback 回调接口
     */
    private void loadLocalData(final LoadSourceCallback<? super ComicDataModel> callback) {
        mLocal.getData(new LoadSourceCallback<ComicDataModel>() {
            @Override
            public void onDataLoaded(ComicDataModel dataModel) {
                callback.onDataLoaded(dataModel);
            }

            @Override
            public void onDataLoadFiled() {
                callback.onDataLoadFiled();
            }
        });
    }

    @Override
    public void saveData(ComicDataModel dataModel) {
        mLocal.saveData(dataModel);
    }

    @Override
    public void refreshData() {
    }

    @Override
    public void offLine() {
        mRemote.offLine();
    }
}
